﻿using AutoMapper;
using MediatR;
using System.Runtime.Intrinsics.X86;
using U.B.DoMain;
using U.B.ErrorCode;
using U.B.Repistory;
using U.B.WriteApi.Command;

namespace U.B.WriteApi.CommandHander
{
    public class AddMenuCommandHander : IRequestHandler<AddMenuCommand, ApiResult<string>>
    {
        private readonly IRepistory<Menu> _menuRepository;
        private readonly IMapper _mapper;
        public AddMenuCommandHander(IRepistory<Menu> menuRepository, IMapper mapper)
        {
            _menuRepository = menuRepository;
            _mapper = mapper;
        }
        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public  Task<ApiResult<string>> Handle(AddMenuCommand request, CancellationToken cancellationToken)
        {
            ApiResult<string> apiResult=new ApiResult<string>();
            var now=DateTime.Now;
            var menulist = _menuRepository.GetAll();
            var menuresult=_mapper.Map<Menu>(request);
            menuresult.CreationDate = now;
            menuresult.Creator = "admin";
            menuresult.Updateor = "";
            menuresult.Updatedate = now;
            menuresult.IsDeleted = false;
            var menucount = menulist.Where(x => x.MenuName == request.MenuName && x.PId == request.PId).Count();
            if (menucount > 0)
            {
                apiResult.code = Renum.添加成功;
                apiResult.Message = Renum.添加成功.ToString();
                return Task.FromResult(apiResult);
            }
            if (menuresult.PId == 0)
            {
               menuresult.PId = 0;
                var Maxorderby = menulist.Where(x => x.PId == 0).Select(x => x.MenuOrder).Max();
                menuresult.MenuOrder = Maxorderby + 1;
            }
            else
            {
                var Sonmenu = menulist.FirstOrDefault(x => x.MenuId == menuresult.PId);
                if (Sonmenu != null)
                {
                    menuresult.MenuOrder = Sonmenu.MenuOrder + 1;
                }
            }
            var a = _menuRepository.Add(menuresult);
            apiResult.code = Renum.添加成功;
            apiResult.Message=Renum.添加成功.ToString();
            return Task.FromResult(apiResult);
        }
    }
}
